package com.sudo.common.ip2region;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @Author：DayDayUp
 * @Create：2023/2/6 9:28
 */
@Data
public class IpInfo {
    /**
     * 国家
     */
    private String country;

    /**
     * 区域
     */
    private String region;

    /**
     * 省
     */
    private String province;

    /**
     * 城市
     */
    private String city;

    /**
     * 运营商
     */
    private String isp;

    public IpInfo(String search){
        String[] split = search.split("\\|");
        if (split.length < 5){
            split = Arrays.copyOf(split, 5);
        }
        this.country = filterZero(split[0]);
        this.region = filterZero(split[1]);
        this.province = filterZero(split[2]);
        this.city = filterZero(split[3]);
        this.isp = filterZero(split[4]);
    }

    private String filterZero(@Nullable String info) {
        if (info == null || BigDecimal.ZERO.toString().equals(info)) {
            return null;
        }
        return info;
    }

    /**
     * 拼接完整的地址
     * @return address
     */
    public String getAddress() {
        Set<String> regionSet = new LinkedHashSet<>();
        regionSet.add(country);
        regionSet.add(region);
        regionSet.add(province);
        regionSet.add(city);
        regionSet.removeIf(Objects::isNull);
        return StringUtils.join(StringUtils.EMPTY, regionSet);
    }

    /**
     * 拼接完整的地址
     * @return address
     */
    public String getAddressAndIsp() {
        Set<String> regionSet = new LinkedHashSet<>();
        regionSet.add(country);
        regionSet.add(region);
        regionSet.add(province);
        regionSet.add(city);
        regionSet.add(isp);
        regionSet.removeIf(Objects::isNull);
        return StringUtils.join(StringUtils.EMPTY, regionSet);
    }
}
